<?php
namespace app\mobile\middleware;

use app\admin\model\UserToken;
use Firebase\JWT\JWT;
use think\Request;
use think\facade\Log;
header("content-type:text/html;charset=utf-8");

/**
 * 检测白名单
 * Class CheckWhite
 *
 * @package app\mobile\middleware
 */
class CheckUser
{
    public function handle(Request $request, \Closure $next)
    {

        $header = $request->header();
        if (empty($header['authorization'])) {
            return msg($header, 401, "你还未登录 请进行登录!");
        }
        $authorization = $header['authorization'];
        $userToken = new UserToken();
        $userTokenInfo  = $userToken->where(['token' => $authorization])->find();
        if (empty($userTokenInfo)){
            return msg([], 401, '未登录或登陆已失效，请重新登陆' );
        }
        if (time() > $userTokenInfo['expire_time']){
            return msg([], 401, '未登录或登陆已失效，请重新登陆' );
        }
        try {
            $uid = $userTokenInfo['uid'];
            $request->user_id = $uid;
            $user = \app\admin\model\User::where("id", $uid)->find();
            if (empty($user)) {
                return msg([], 401, "用户不存在!");
            }
            $request->userInfo = $user;
        } catch (\Exception $e) {
            return msg([], 401, '未登录或登陆已失效，请重新登陆' . $e->getMessage());
        }
        return $next($request);
    }
}